import {useKeyPress} from "ahooks";
import {useDispatch} from "react-redux";
import {
    copySelectedComponent,
    pasteCopiedComponent,
    removeSelectedComponent, selectNextComponent,
    selectPrevComponent
} from "../store/componentsReducer";
import {ActionCreators} from "redux-undo";

function isActiveElementValid() {
    const activeElem = document.activeElement
    // 为增加 dnd-kit 之前
    // return activeElem === document.body;
    // 增加 dnd-kit 之后
    if (activeElem === document.body) return true
    return !!activeElem?.matches('div[role="button"]');
}

function useBindCanvasKeyPress() {
    const dispatch = useDispatch()
    // 删除组件
    useKeyPress(['backspace', 'delete'], () => {
        if (!isActiveElementValid()) return
        dispatch(removeSelectedComponent())
    })

    useKeyPress(['ctrl.c', 'meta.c'], () => {
        if (!isActiveElementValid()) return
        dispatch(copySelectedComponent())
    })
    useKeyPress(['ctrl.v', 'meta.v'], () => {
        if (!isActiveElementValid()) return
        dispatch(pasteCopiedComponent())
    })
    useKeyPress(['uparrow'], () => {
        if (!isActiveElementValid()) return
        dispatch(selectPrevComponent())
    })
    useKeyPress('downarrow', () => {
        if (!isActiveElementValid()) return
        dispatch(selectNextComponent())
    })
    useKeyPress(['ctrl.z', 'meta.z'], () => {
        if (!isActiveElementValid()) return
        dispatch(ActionCreators.undo())
    }, {exactMatch: true})
    useKeyPress(['ctrl.shift.z', 'meta.shift.z'], () => {
        if (!isActiveElementValid()) return
        dispatch(ActionCreators.redo())
    }, {exactMatch: true})
}

export default useBindCanvasKeyPress